package net.studou.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import net.studou.exception.ShopKeeperException;
import net.studou.exception.SystemException;

import org.springframework.stereotype.Component;

@Component("shopKeeperService")
public class ShopKeeperService {

	public void checkShopKeeper(String tbUrl, String keeper) throws ShopKeeperException {
		String example = getShopKeeper("http://shop63178083.taobao.com");
		if (!"caicai_vip".equals(example)) {
			throw new SystemException("Shopkeeper != caicai_vip");
		}
		String shopKeeper = getShopKeeper(tbUrl);
		if (shopKeeper == null || !shopKeeper.equals(keeper)) {
			throw new ShopKeeperException("Two shopKeeper is not equals");
		}
	}

	public String getShopKeeper(String tbUrl) {
		String shopper = null;

		try {
			URL url = new URL(tbUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while ((line = br.readLine()) != null) {
				if (line.contains("nickName")) {
					String flag = "nickName:";
					shopper = line.substring(line.indexOf(flag) + flag.length(), line.length() - 2).trim().substring(1);
					shopper = URLDecoder.decode(shopper, "utf-8");
					break;
				}
			}
		} catch (Exception e) {
			throw new SystemException("Get shoppkeeper error", e);
		}

		return shopper;
	}

}
